﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SignalR;
using System.Reflection;
using YiShop.Framework.Attributes;

namespace YiShop.Framework.Extensions
{
    public static class HubRouteExtensions
    {
        /// <summary>
        /// 批量注册带有 [HubRoute] 特性的 Hub
        /// </summary>
        public static IEndpointRouteBuilder MapHubsByAttribute(
            this IEndpointRouteBuilder endpoints,
            params Assembly[] assemblies)
        {
            // 若未指定程序集，默认扫描所有已加载程序集
            if (assemblies == null || assemblies.Length == 0)
            {
                assemblies = AppDomain.CurrentDomain.GetAssemblies();
            }

            var mapHubMethod = typeof(HubEndpointRouteBuilderExtensions).GetMethods().First(m => m.Name == "MapHub" && m.IsGenericMethod);

            foreach (var assembly in assemblies)
            {
                var hubTypes = assembly.GetTypes()
                    .Where(t => t.IsClass &&
                                 !t.IsAbstract &&
                                 t.IsSubclassOf(typeof(Hub)) &&
                                 t.GetCustomAttribute<HubRouteAttribute>() != null);

                foreach (var hubType in hubTypes)
                {
                    var route = hubType.GetCustomAttribute<HubRouteAttribute>()!.Route;
                    // 构造泛型方法 MapHub<THub>
                    var genericMethod = mapHubMethod.MakeGenericMethod(hubType);

                    // 调用方法: endpoints.MapHub<THub>(route)
                    genericMethod.Invoke(
                        obj: null,
                        parameters: new object[] { endpoints, route });
                }
            }

            return endpoints;
        }
    }
}